<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
      :needOperateAffair="true"
      :operateAffairData="affairTableInfo"
      @returnBack="returnBack"
    >
      <template v-slot:full-button>
        <PopoverPrint
          ref="popoverShow"
          v-model:popoverVisible="popoverVisible"
          :canPrint="canComplete"
          :templateArr="templateArr"
          @tempClick="tempClick"
          @print="print"
        ></PopoverPrint>
        <el-button
          v-if="canStorage && $permission('useReturnStoreApplication:store')"
          @click="storage"
          >入库</el-button
        >
        <el-button v-if="canCancelPut" @click="_cancelPut()"
          >取消上架</el-button
        >
        <!-- <el-button
          v-if="
            canStorageAndPutShelf &&
            $permission('useReturnStoreApplication:storeAndPutShelf')
          "
          @click="storeAndPutShelf"
          >入库并上架</el-button
        > -->
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <basic-information
            :info="infoList"
            :label-width="infoList.labelWidth"
          >
          </basic-information>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <div class="flex_full_item">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :check-box="false"
                :tab-index="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
              >
              </page-table>
            </div>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <individual-details
      v-if="individualInfo.visible"
      v-model:show-dialog="individualInfo.visible"
      :query="individualInfo.query"
      :info="individualInfo.info"
    />
    <PageDialog
      v-show="dialogUserInfo.visible"
      :title="dialogUserInfo.title"
      v-model:visible="dialogUserInfo.visible"
      :width="dialogUserInfo.width"
      :bt-loading="dialogUserInfo.btLoading"
      :bt-list="dialogUserInfo.btList"
      @reset="handleClose"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formUserInfo.ref"
        :data="formUserInfo.data"
        :field-list="formUserInfo.fieldList"
        :label-width="formUserInfo.labelWidth"
        :list-type-info="listTypeInfo"
      >
      </page-form>
    </PageDialog>
  </div>
</template>

<script setup name="useReturnStorageDetails">
import {
  getUseReturnExportDetailCustomizeList,
  detailUseReturnExport,
  returnExportInBound,
  exportUseReturnStoreApplication,
  getReturnStorePrint,
  returnExportInBoundAndPutShelf,
  cancelPut,
} from '@/api/use.js'
import { orderAffairAll } from '@/api/affair'
import { getCustomizeSetting } from '@/api/customize'
import { fatchTemplateByCode, getRrgUserAll } from '@/api/base'
import IndividualDetails from './IndividualDetails'
import { ElMessageBox } from 'element-plus'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'id', 'orderNo'])

const title = ref('退回入库单详情')
const infoList = ref({
  data: {},
  fieldList: [
    { label: '出库单号', value: 'orderNo', type: 'text' },
    { label: '申请单号', value: 'applicationOrderNo', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '退回人', value: 'applicationUserName', type: 'text' },
    { label: '退回部门', value: 'exportDeptName', type: 'text' },
    { label: '退入部门', value: 'storeDeptName', type: 'text' },
    { label: '退出仓库', value: 'exportDepotName', type: 'text' },
    { label: '退入仓库', value: 'storeDepotName', type: 'text' },
    { label: '退回日期', value: 'exportTime', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '更新人', value: 'updateUserName', type: 'text' },
    { label: '更新时间', value: 'updateTime', type: 'text' },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'text',
    },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    { label: '备注', value: 'remark', type: 'popover' },
  ],
  labelWidth: '130px',
})
const filterInfo = ref({
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {},
    customizeUserVO: {},
  },
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '个体详情',
        event: showDetail,
        show: true,
      },
    ],
  },
})
const fullInfo = ref({
  btnList: [
    // {label : '入库' , event : storage ,show: true},
    {
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('useReturnStorageApplication:exportExcel'),
    },
  ],
})
const affairTableInfo = ref({
  api: orderAffairAll,
  query: {
    orderType: 71,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})
const individualInfo = ref({
  visible: false,
  query: {},
  info: {},
})
const dialogUserInfo = ref({
  visible: false,
  title: '选择上架人员',
  btLoading: false,
  width: '400px',
  btList: [
    {
      label: '关闭',
      event: handleClose,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      event: saveputShelfUser,
      show: true,
    },
  ],
})
const formUserInfo = ref({
  data: {
    id: '',
    putShelfUser: -2,
  },
  fieldList: [
    {
      label: '姓名',
      value: 'putShelfUser',
      type: 'select',
      filterable: true,
      list: 'userList',
      event: 'userName',
    },
  ],
})
const listTypeInfo = ref({
  userList: [],
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canComplete = computed(() => {
  return proxy.$permission('useReturnStoreApplication:print')
})
const canStorage = computed(() => {
  return infoList.value.data.status === 1
})
const canStorageAndPutShelf = computed(() => {
  return (
    infoList.value.data.status === 1 &&
    infoList.value.data.isCargoSpaceManage === 1
  )
})
const canCancelPut = computed(() => {
  return (
    proxy.$permission('useReturnStoreApplication:cancelPut') &&
    infoList.value.data.status === 4
  )
})

watch(
  () => props.visible,
  (newVal) => {
    showDialog.value = newVal
  },
  {
    immediate: true,
  }
)

setData()
function setData() {
  let obj = {
    orderNo: {
      label: '单号',
      value: 'orderNo',
      componentType: 'input',
      show: false,
      // type: 'slot',
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      minWidth: '150px',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('useReturnStoreApplication:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('useReturnStoreApplication:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      componentType: 'price',
      permission: !proxy.$permission('useReturnStoreApplication:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
      show: false,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
  getUserList()
}
//获取人员列表
function getUserList() {
  let params = {
    sort: 'create_time desc',
  }
  getRrgUserAll(params).then((res) => {
    if (res && res.success) {
      let arr = [{ key: '暂不选择', value: -2, userName: '' }]
      if (res.data && res.data.length) {
        let data = res.data.map((item) => {
          return {
            key: item.name,
            value: item.id,
            userName: item.userName,
          }
        })
        listTypeInfo.value.userList = arr.concat(data)
      }
    }
  })
}
function storeAndPutShelf() {
  // 方法名称
  dialogUserInfo.value.visible = true
  formUserInfo.value.data.id = props.id
  // returnExportInBoundAndPutShelf
}
//上架
function saveputShelfUser() {
  returnExportInBoundAndPutShelf(formUserInfo.value.data).then((res) => {
    if (res && res.success) {
      getMain()
      getList()
      handleClose()
    }
  })
}
//关闭选择拣货人员弹窗
function handleClose() {
  dialogUserInfo.value.visible = false
  formUserInfo.value.data = {
    id: '',
    putShelfUser: -2,
  }
}
function returnBack() {
  emits('returnBack', false)
}
function handleEvent() {
  // switch (event) {
  //     // 对表格获取到的数据做处理
  // }
}

function storage() {
  ElMessageBox.confirm('此操作将更新数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      let param = []
      param.push(infoList.value.data.id)
      returnExportInBound(param).then((res) => {
        if (res.success) {
          getMain()
        }
      })
    })
    .catch((e) => {})
}
//取消上架
function _cancelPut() {
  proxy
    .$confirm('确认取消上架吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      cancelPut(props.id).then((resp) => {
        if (resp && resp.success) {
          getMain()
        }
      })
    })
    .catch(() => {})
}
//个体详情
function showDetail(row) {
  let ids
  if (row.groupConcatIds) {
    //未定义表示没有分组条件
    ids = row.groupConcatIds
  } else {
    ids = '' + row.id
  }
  individualInfo.value.query = {
    id: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: ids,
    },
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.id,
    },
  }
  individualInfo.value.info = row
  individualInfo.value.visible = true
}
//导出excel
function exportExcel() {
  exportUseReturnStoreApplication(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}

const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'useReturnStoreDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            applicationId: infoList.value.data.id,
            orderId: infoList.value.data.id,
            orderNo: infoList.value.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      applicationId: infoList.value.data.id,
      orderId: infoList.value.data.id,
      orderNo: infoList.value.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      orderId: infoList.value.data.id,
      tempCode: 'useReturnStoreDetail',
      orderType: 71,
    })
  } catch (error) {}
}
function getList() {
  getUseReturnExportDetailCustomizeList(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
    }
  })
}
function getMain() {
  detailUseReturnExport(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
      getList()
    }
  })
}
function getCustomize() {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey:
      'useReturnExportOrderInDetail-com.slip.spd.entity.vo.use.UseReturnExportOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      getMain()
    }
  })
}
</script>

<style scoped></style>
